package org.jash.user.register

import com.example.common.mvi.BaseActivity
import org.jash.user.databinding.ActivityRegisterBinding
import org.jash.user.R
import android.widget.Toast
import android.content.Intent
import com.alibaba.android.arouter.facade.annotation.Route

import androidx.activity.viewModels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.SPUtils

@Route(path = "/user/RegisterActivity")
class RegisterActivity : BaseActivity<ActivityRegisterBinding, RegisterViewModel, RegisterIntent, RegisterViewState>() {
	override val viewModel: RegisterViewModel by viewModels {
		object : ViewModelProvider.Factory {
			override fun <T : ViewModel> create(modelClass: Class<T>): T {
				return RegisterViewModel(RegisterRepository()) as T
			}
		}
	}

	override fun getLayoutId(): Int = R.layout.activity_register

	override fun setupViews() {
		binding.ivBack.setOnClickListener { finish() }
		binding.btnRegister.setOnClickListener {
			val username = binding.etPhone.text?.toString()?.trim().orEmpty()
			val password = binding.etPassword.text?.toString()?.trim().orEmpty()
			val repassword = binding.etRepassword.text?.toString()?.trim().orEmpty()

			if (username.isEmpty() || password.isEmpty()|| repassword.isEmpty()) {
				Toast.makeText(this, "请输入手机号和密码", Toast.LENGTH_SHORT).show()
				return@setOnClickListener
			}

			if(password!=repassword){
				Toast.makeText(this, "俩次密码不一致", Toast.LENGTH_SHORT).show()
				return@setOnClickListener
			}
			sendIntent(org.jash.user.register.RegisterIntent.Register(username, password))
		}
	}

	override fun renderViewState(state: org.jash.user.register.RegisterViewState) {
		binding.btnRegister.isEnabled = !state.isLoading
		if (state.isLoading) {
			// 可根据需要显示加载中UI
		}
		if (state.isSuccess) {
			val username = binding.etPhone.text?.toString()?.trim().orEmpty()
			val password = binding.etPassword.text?.toString()?.trim().orEmpty()
			// 存储用户名和密码
			SPUtils.getInstance().put("username", username)
			SPUtils.getInstance().put("password", password)
			Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show()
			// 返回登录页面并自动填充
			val intent = Intent()
			intent.putExtra("username", username)
			intent.putExtra("password", password)
			setResult(RESULT_OK, intent)
			finish()
			// 或者用 ARouter 传参
			// ARouter.getInstance().build("/user/LoginActivity")
			//     .withString("username", username)
			//     .withString("password", password)
			//     .navigation()
		}
		if (state.error != null) {
			Toast.makeText(this, state.error.toString(), Toast.LENGTH_LONG).show()
		}
	}
}
